#!/usr/bin/python

import sys
import os
import re
from ssh_shake import ssh_shake as ssh
from mount import mount as mon

def install(monit):
    os.system("ssh "+monit+" \"yum -y install mongodb-server mongodb\"")
    return

def mount(ip,dev):
    if dev:
        os.system('ssh '+ip+' "mkdir -p /var/lib/mongodb"')
        M = mon()
        M.mount_disk(ip,dev,"/var/lib/mongodb")
   
def getLocalIp(monit):
    ip_list = []
    reader = os.popen("ssh "+monit+" ip addr")
    temps = reader.readlines()
    for temp in temps:
	result = re.search(r"inet (\d+\.\d+\.\d+\.\d+)/\d+ (scope|brd)",temp)
	if result:
	   print result.group(0)
	   ip_list.append(result.group(1))
    return ip_list
    

def config(ips,monit):
    ip = ips[0]
    for i in range(1,len(ips)):
	ip += ","+ips[i]
    reader = open("./config/monitor/mongod.conf","r")
    writer = open("/etc/mongod.conf","w")
    text = reader.readlines()
    reader.close()
    writer.writelines(text)
    writer.write("bind_ip = "+ip)
    writer.close()
    os.system("scp /etc/mongod.conf root@"+monit+":/etc/")
    return

def run(monit):
    os.system("ssh "+monit+" \"systemctl enable mongod.service\"")
    os.system("ssh "+monit+" \"systemctl start mongod.service\"")
    return

def create(monit,ip='127.0.0.1',port=22,user="ceilometer",pwd="123456a?",roles="dbAdmin"):
    S = ssh()
    conn = S.create(monit,port)
    stdin,stdout,stderr = conn.exec_command("mongo --host "+ip+" --eval 'db = db.getSiblingDB(\"ceilometer\");db.createUser({user: \""+user+"\",pwd: \""+pwd+"\",roles:[\"readWrite\", \""+roles+"\" ]})'")
#    if stdout != None:
#        print stdout.readlines()
#    else:
#        print stderr.readlines()
#    os.system("ssh "+monit+" \'mongo --host "+ip+" --eval 'db = db.getSiblingDB(\"ceilometer\");db.createUser({user: \""+user+"\",pwd: \""+pwd+"\",roles: [ \"readWrite\", \""+roles+"\" ]})'")
    return


if __name__ == "__main__":
    create("172.22.29.177","172.22.29.177")
